#include <sstream>
#include <stdlib.h>
#include <string.h>

#include "SSLWrapper.hpp"
#include "ListenSocket.hpp"
#include "Logger.hpp"
#include "ConnectionHandlerHTTPS.hpp"

int protected_main(int argc, char** argv) {
	if (argc != 5) {
		std::cerr << "Syntax:" << std::endl;
		std::cerr << argv[0] << " <naive|CA-File> <Port> <Zertifikat> <privater Schlüssel>" << std::endl;
		exit(1);
	}

	//initialize SSL
	SSL_CTX* context = SSLWrapper::init();

	//configure it
	if (strcmp("naive", argv[1]) == 0) {
		SSLWrapper::setVerifyMode(context, SSL_VERIFY_NONE);

	} else {
		SSLWrapper::loadHierarchy(context, std::string(argv[1]));
		SSLWrapper::setVerifyMode(context, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
	}
	SSLWrapper::loadCertificate(context, std::string(argv[3]));
	SSLWrapper::loadPrivatekey(context, std::string(argv[4]));

	ListenSocket socket = ListenSocket(IP("127.0.0.1"), atoi(argv[2]));
  while (true) {	
		ConnectionHandler* newConn = new ConnectionHandlerHTTPS(context);
		socket.handleConnection(newConn);
		Logger::log(Logger::INFO, "Host connected to server.");
	}
	
	return 0;
}

int main(int argc, char** argv) {
//	return protected_main(argc, argv);

	try {
		return protected_main(argc, argv);
	} catch (const GenericException& e) {
		e.terminate();
	}
	return 1;
}
